package com.md.api.scheduled;

import com.md.api.common.utils.DateUtils;
import com.md.api.common.utils.HolidayUtil;
import com.md.api.common.utils.StringUtils;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.constants.SysConstants;
import com.md.api.entity.enums.ChangeStatus;
import com.md.api.entity.enums.ShoppingStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName SystemTask
 * @Description 定时任务
 * @Author 刘杰
 * @Date 2019/8/8 10:09
 * @Version 1.0
 **/
@Component
@Slf4j
public class SystemTask {
    @Resource
    ShoppingOrderMapper shoppingOrderMapper;
    @Resource
    ShoppingOrderDetailMapper shoppingOrderDetailMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    SysConfigMapper configMapper;
    @Resource
    SiteServiceContentMapper serviceContentMapper;
    @Resource
    UserBalanceRecordMapper balanceRecordMapper;
    @Resource
    SiteServicePredetermineRecordMapper predetermineRecordMapper;
    @Resource
    ShoppingChangeOrderMapper changeOrderMapper;
    //定时商城订单7天完成
    @Scheduled(cron = "0 0 20 * * ?")
    public void handNoShoppingConfirm(){
        List<ShoppingOrderDetail> list = shoppingOrderMapper.getNotConfirmOrder();
        for (ShoppingOrderDetail detail:list){
            detail.setStatus(ShoppingStatus.COMPLETED.value());
            detail.setIsConfirm(1);
            shoppingOrderDetailMapper.confirmOrder(detail);
            commissionShare(detail);
        }
    }


    @Async
    public void commissionShare(ShoppingOrderDetail detail) {
        ShoppingOrder order = shoppingOrderMapper.getByOrderNo(detail.getOrderNo());
        UserInfo user = userMapper.getByUserId(order.getUserId());
        if (StringUtils.isEmpty(user.getParentUserId())) return;
        UserInfo secondUser = userMapper.getByUserId(user.getParentUserId());
        SysConfig config = configMapper.getByKey(SysConstants.SECOND_SHOPPING_RATE);
        if (null!=config&&secondUser.getUserType()==0){
            UserBalanceRecord balanceRecord = new UserBalanceRecord();
            balanceRecord.setBalance(detail.getPrice()*Double.valueOf(config.getConfigValue()));
            balanceRecord.setUserId(secondUser.getUserId());
            balanceRecord.setRecordName("商城佣金分成");
            balanceRecord.setRecordType(1);
            balanceRecord.setOrderNo(order.getOrderNo());
            balanceRecordMapper.insert(balanceRecord);

            BigDecimal num1 = new BigDecimal(new Double(secondUser.getBalance()).toString());
            BigDecimal num2 = new BigDecimal(new Double(order.getCommission()).toString());
            user.setBalance(num1.add(num2).doubleValue());
            userMapper.updateBalance(secondUser);
        }
        if (StringUtils.isEmpty(secondUser.getParentUserId())) return;
        SysConfig fconfig = configMapper.getByKey(SysConstants.SECOND_SHOPPING_RATE);
        UserInfo firstUser = userMapper.getByUserId(secondUser.getParentUserId());
        if (firstUser.getUserType()==1) return;
        UserBalanceRecord balanceRecord = new UserBalanceRecord();
        balanceRecord.setBalance(detail.getPrice()*Double.valueOf(fconfig.getConfigValue()));
        balanceRecord.setUserId(firstUser.getUserId());
        balanceRecord.setRecordName("商城佣金分成");
        balanceRecord.setRecordType(1);
        balanceRecord.setOrderNo(order.getOrderNo());
        balanceRecordMapper.insert(balanceRecord);
        BigDecimal num1 = new BigDecimal(new Double(firstUser.getBalance()).toString());
        BigDecimal num2 = new BigDecimal(new Double(order.getCommission()).toString());
        user.setBalance(num1.add(num2).doubleValue());
        userMapper.updateBalance(firstUser);
    }

    /**
     * 定时生成车检预订信息记录
     */
    @Scheduled(cron = "0 10 15 * * *")
    public void handleServicePredetermine(){
        List<SiteServiceContent> rList = serviceContentMapper.selectAll(null);
        if (!CollectionUtils.isEmpty(rList)) {
            for(SiteServiceContent serviceContent:rList){
                try {
                    String serviceId = serviceContent.getServiceId();
                    Integer timeLimit = serviceContent.getTimeLimit();
                    Date nowDate = DateUtils.getNowDate();
                    Date maxDate =null;
                    //获取已生成记录的最大日期
                    String maxDateStr = predetermineRecordMapper.getMaxDate(serviceId);
                    int datePoordDay = 0;
                    if (StringUtils.isEmpty(maxDateStr)){
                        maxDate = nowDate;
                    }else{
                        maxDate = DateUtils.formatToDate(maxDateStr);
                        datePoordDay = DateUtils.getDatePoordDay(maxDate, nowDate)+1;
                    }

                    if (maxDate.getTime()>=DateUtils.add(nowDate, Calendar.DATE, 6).getTime()){
                        continue;
                    }

                    Integer satOnline = serviceContent.getSatOnline();
                    Integer sunOnline = serviceContent.getSunOnline();
                    Integer holidayOnline = serviceContent.getHolidayOnline();

                    for (int day = 0; day < 30-datePoordDay; day++) {
                        LocalTime timeRangeStart = serviceContent.getTimeRangeStart();
                        LocalTime timeRangeEnd = serviceContent.getTimeRangeEnd();
                        Date date = DateUtils.add(nowDate, Calendar.DATE, datePoordDay + day);
                        String workingDay = HolidayUtil.isWorkingDay(DateUtils.formatD(date));
                        if (workingDay.equals("2")&&sunOnline==0){
                            continue;
                        }
                        if (workingDay.equals("1")&&satOnline==0){
                            continue;
                        }
                        if (workingDay.equals("3")&&holidayOnline==0){
                            continue;
                        }
                        if (workingDay.equals("2")&&sunOnline==1){
                            timeRangeStart = serviceContent.getSunTimeRangeStart();
                            timeRangeEnd = serviceContent.getSunTimeRangeEnd();
                        }else if (workingDay.equals("1")&&satOnline==1){
                            timeRangeStart = serviceContent.getSatTimeRangeStart();
                            timeRangeEnd = serviceContent.getSatTimeRangeEnd();
                        }
                        long minutesBetween = ChronoUnit.MINUTES.between(timeRangeStart, timeRangeEnd);
                        //应该有多少条记录
                        int dif = (int) Math.floor(minutesBetween / timeLimit);
                        LocalTime nextRecordTime = timeRangeStart.plusMinutes(0);
                        for (int i = 1; i <= dif+2; i++) {
                            if (nextRecordTime.isBefore(timeRangeEnd)) {
                                System.out.println("Creating record at: " + nextRecordTime);
                                SiteServicePredetermineRecord predetermineRecord = new SiteServicePredetermineRecord();
                                String predetermineId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
                                predetermineRecord.setPredetermineId(predetermineId);
                                predetermineRecord.setServiceId(serviceId);
                                predetermineRecord.setPredetermineDate(date);
                                predetermineRecord.setPredetermineTime(nextRecordTime);
                                predetermineRecord.setTotalCount(serviceContent.getTotalCount());
                                predetermineRecord.setPredetermineCount(0);

                                if (workingDay.equals("3")&&holidayOnline==0){
                                    predetermineRecord.setStatus(0);
                                }else if (workingDay.equals("2")&&sunOnline==0){
                                    predetermineRecord.setStatus(0);
                                }else if (workingDay.equals("1")&&satOnline==0){
                                    predetermineRecord.setStatus(0);
                                }else{
                                    predetermineRecord.setStatus(1);
                                }
                                predetermineRecordMapper.insert(predetermineRecord);
                                nextRecordTime = timeRangeStart.plusMinutes(timeLimit*i);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("SystemTask.handleRoomPredetermine() error",e);
                    continue;
                }
            }
        }
        log.info("定时生成车检预订信息记录完毕");
    }


    //定时商城换货订单7天完成
    @Scheduled(cron = "0 0 20 * * ?")
    public void handNoShoppingChangeConfirm(){
        List<ShoppingChangeOrder> list = changeOrderMapper.getNotConfirmOrder();
        for (ShoppingChangeOrder changeOrder:list){
            changeOrder.setChangeStatus(ChangeStatus.COMPLETED.value());
            changeOrderMapper.update(changeOrder);
            ShoppingOrderDetail detail = shoppingOrderDetailMapper.getDetail(changeOrder.getOrderNo(),changeOrder.getSkuId());
            detail.setStatus(ShoppingStatus.CHANGE_COMPLETED.value());
            shoppingOrderDetailMapper.updateStatus(detail);
        }
    }
}
